const CryptoJS = require("crypto-js");
const {
    SECRE_TKYE
} = require('@utils/constant');
//将具有父子关系的原始数据格式化成树形结构数据(id, pid)
function toTreeData(data) {
    const tree = data.filter(father => { //循环所有项
        let branchArr = data.filter(child => {
            return father.id == child.pid; //返回每一项的子级数组
        })
        if (branchArr.length > 0) {
            father.children = branchArr; //如果存在子级，则给父级的children的属性或创建children属性，并赋值
        }
        return father.pid == '';
    })

    return tree;
}

//去重
function toSingleData(data, id) {
    let map = new Map();
    for (let item of data) {
        if (!map.has(item[id])) {
            map.set(item[id], item);
        }
    }
    return [...map.values()];
}

//获取操作系统ip
function getClientIP(req) {
    return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
        req.connection.remoteAddress || // 判断 connection 的远程 IP
        req.socket.remoteAddress || // 判断后端的 socket 的 IP
        req.connection.socket.remoteAddress
};

//'aa,bb,cc'转'"aa","bb","cc"',一般用于删除多条记录
function toItem(params) {
    let ary = params.split(',');
    let items = '';
    for (let i = 0; i < ary.length; i++) {
        if (i === 0) {
            items = `"${ary[i]}"`
        } else {
            items = items + ',' + `"${ary[i]}"`
        }
    }
    return items;
}

function setAes(data) {
    return CryptoJS.AES.encrypt(JSON.stringify(data), SECRE_TKYE).toString();
}

function getAes(data) {
    const bytes = CryptoJS.AES.decrypt(data, SECRE_TKYE);
    return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
}

function format(time3) {
    //将时间戳格式转换成年月日时分秒
    var date = new Date(time3);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    var strDate = Y + M + D + h + m + s;
    // console.log('输出内容:', strDate)
    return strDate
}
module.exports = {
    toTreeData,
    toSingleData,
    getClientIP,
    toItem,
    setAes,
    getAes,
    format,
}